<?php

    class EventController extends Zend_Controller_Action
    {

        private $commonModel;
        private $user;

        public function init()
        {
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (!empty($y))
            {
                $this->user_id = $x->read()->user_id;
            }
            $this->user = (array) $y;
            $this->commonModel = new Application_Model_Common;
        }

        public function indexAction()
        {
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (empty($y))
            {
                $this->redirect("");
            }

            $event_id = $this->_getParam("id");
            $this->view->bodyClass = "create-event";
            $categoryArr = $this->commonModel->getAllRecordDetail('category', '1', 'category_name');
            $this->view->categoryArr = $categoryArr;
//            $countryArr = $this->commonModel->getAllRecordDetail('country', '1', 'country_name');
//            $this->view->countryArr = $countryArr;
            $this->view->event_group_type = "limited";

            if (!empty($event_id))
            {
                $commonModel = new Application_Model_Common;
                //$data = $commonModel->getdata(TABLE_EVENTS, 'event_id = '.$event_id);
                $data = $commonModel->getAdapter()->select()->from(TABLE_EVENTS)
                        ->join(TABLE_CATEGORY, TABLE_CATEGORY . ".category_id = " . TABLE_EVENTS . ".event_cat_id")
                        ->join(TABLE_SUB_CATEGORY, TABLE_SUB_CATEGORY . ".subcategory_id = " . TABLE_EVENTS . ".event_subcat_id")
//                        ->join(TABLE_COUNTRY, TABLE_COUNTRY . ".country_id = " . TABLE_EVENTS . ".event_country")
                        ->where("event_id = " . $event_id);

                //prd($data->__toString());
                $data = $data->query()->fetch();

//                prd($data);
//                $country_arr = $commonModel->getdata(TABLE_COUNTRY, "country_id=" . $data["event_country"]);
                $subcat_Arr = $commonModel->getdata(TABLE_SUB_CATEGORY, "subcategory_id=" . $data["event_subcat_id"]);
//                $data["event_country"] = $country_arr["country_name"];
                $data["event_subcat_id"] = $subcat_Arr["subcategory_name"];
                $data['event_date'] = json_decode($data['event_date']);
                $data['event_end_date'] = json_decode($data['event_end_date']);

                $data["event_country"] = $data["event_location"];
//                prd($data);

                $this->view->assign($data);
            }
            else
            {
                
            }

            if (!is_dir("resources/temp/" . $this->user_id))
                @mkdir("resources/temp/" . $this->user_id);
            else
            {
                foreach (glob("resources/temp/" . $this->user_id . "/*") as $filename)
                {
                    @unlink($filename);
                }
            }
        }

        public function eventdetailAction()
        {
            if ($this->getParam("enc_event_id"))
            {
                $enc_event_id = trim($this->getParam("enc_event_id"));
                $event_id = getEncryptedString($enc_event_id, "decode");
//                prd($event_id);
                $model = new Application_Model_Common();
                $this->view->event_id = $event_id;
//                prd($event_id);
                $custom_model = new Application_Model_Custom();

                $records = $custom_model->getAllEventDetails("event_id=$event_id");
//                prd($records);
                // redirect to homepage if the event has ended, only after one week of ended event
                if ($records[0]["event_ended"] == "1")
                {
                    $event_end_date = getEventDate($records[0]["event_end_date"]);
                    $end_date_plus_one_week = strtotime("+7 days", strtotime($event_end_date));
                    if ($end_date_plus_one_week <= time())
                    {
                        $_SESSION["messageError"] = "This event posting has been expired";
//                        $_SESSION["messageError"] = "The event you are trying to look for has either ended or expired";
//                        $this->redirect("");
                    }
                }

                $event_chat_records = $model->getAllRecordFromInnerJoin(array("ec" => TABLE_EVENT_CHAT), array("u" => TABLE_USERS), "u.user_id=ec.ec_user_id", "ec.ec_event_id = $event_id", "ec.ec_id ASC", "200");

                $user_id = !isset($this->user_id) ? "" : $this->user_id;
                $this->view->alldata = $records[0];

                //prd($event_chat_records);

                $this->view->chatRecords = $event_chat_records;
                $this->view->logged_user_id = $user_id;

                $event_join_records = $model->getTotalCount("ej_id", TABLE_EVENT_JOIN, "ej_event_id=" . $records[0]["event_id"] . " AND ej_is_accepted = '1' AND ej_is_invited = '0'");
                $joined_count = $event_join_records["totalcount"];
                $this->view->availableSpots = $records[0]["event_group_size"] - $joined_count;

                $is_joined = "no";
                $event_join_status = "0";
                if (!empty($user_id))
                {
//                    $is_already_joined = $model->is_exists(TABLE_EVENT_JOIN, "ej_event_id=" . $records[0]["event_id"] . " AND ej_user_id = $user_id");
                    $is_already_joined = $model->is_exists(TABLE_EVENT_JOIN, "ej_event_id=" . $records[0]["event_id"] . " AND ej_user_id = $user_id  AND ej_is_invited = '0'");

                    if (!empty($is_already_joined))
                    {
                        $is_joined = "yes";
                        if ($is_already_joined["ej_is_accepted"] == "1")
                            $event_join_status = "1";
                    }
                }

                $is_bookmarked = "no";

                $this->view->isJoined = $is_joined;
                $this->view->eventJoinStatus = $event_join_status;

                $joined_user_records = $model->getAllRecordFromInnerJoin(array("ej" => TABLE_EVENT_JOIN), array("u" => TABLE_USERS), "u.user_id=ej.ej_user_id", "ej_event_id=" . $records[0]["event_id"] . " and ej_is_accepted = '1' and ej_is_invited='0' ", "ej.ej_id");
                $this->view->usersAttending = $joined_user_records;

                $x = new Zend_Auth_Storage_Session('User_Auth');
                $y = $x->read();
                if (empty($y))
                    $this->view->isLoggedIn = "no";
                else
                {
                    $check_bookmark = $model->is_exists(TABLE_EVENT_BOOKMARK, "eb_event_id=" . $records[0]["event_id"] . " AND eb_user_id=$user_id");
                    if (!empty($check_bookmark))
                        $is_bookmarked = "yes";

                    $this->view->isLoggedIn = "yes";
                }

                $this->view->isBookmarked = $is_bookmarked;
                $this->view->isUsersOwnEvent = "no";
                if ($this->view->isLoggedIn == "yes")
                {

                    //check if the opened event is user's own event
                    $user_events = $this->getMyEvents($user_id);

                    //prd($user_events);
                    if (in_array($event_id, $user_events))
                    {
                        $this->view->isUsersOwnEvent = "yes";
                        $waiting_records = $model->getAllRecordFromInnerJoin(array("ej" => TABLE_EVENT_JOIN), array("u" => TABLE_USERS), "u.user_id=ej.ej_user_id", "ej_event_id=" . $records[0]["event_id"] . " and ej_is_accepted = '0' and ej_is_invited='0'", "ej.ej_id");
                    }
                    $this->view->usersWaiting = $waiting_records;
                }

                //prd($this->view->isUsersOwnEvent);

                $host_records = $model->getAllRecordFromLeftJoin(array("e" => TABLE_EVENTS), array("u" => TABLE_USERS), "u.user_id=e.event_created_by", "e.event_id=$event_id");
//                prd($host_records);
                $host_id = $host_records[0]["user_id"];
                $hostEventCounts = $custom_model->getUserEventsCounts($host_id);
                $new_array = array_merge($host_records[0], $hostEventCounts);
//                $host_rating_arr = $custom_model->getRating($host_id);
//                $rating = @($host_rating_arr["totalrating"] / $host_rating_arr["totalvotes"]);
//                if (empty($rating))
//                    $rating = "0";

//                $new_array["host_rating"] = $rating;
                $new_array["host_rating"] = round($custom_model->getEventAverageRating($host_id));

                if (empty($new_array["user_education"]))
                    $new_array["user_education"] = "NA";
                if (empty($new_array["user_work"]))
                    $new_array["user_work"] = "NA";

                if (!empty($user_id))
                    $this->view->friendGroupsAndFriends = $custom_model->getFriendsAndGroups($user_id);

                $this->view->hostDetails = $new_array;
                $this->view->hostOtherUsersComments = $custom_model->getMyReviewsList($host_id);
                $this->view->hostCreatedEvents = $this->getCreatedEvent($host_id);
                $this->view->hostTotalRating = round($custom_model->getEventAverageRating($host_id));

                $myevents = "";
                if (!empty($this->user_id) && isset($this->user_id))
                    $myevents = $model->getAllRecordDetail(TABLE_EVENTS, "event_active = '1' AND event_created_by = " . $this->user_id, "event_id DESC");

                $this->view->myEvents = $myevents;
            }
            else
            {
                $this->redirect("");
            }
        }

        public function joineventAction()
        {
            if ($this->getParam("enc_event_id") && isset($this->user_id))
            {
                $user_id = $this->user_id;
                $event_id = getEncryptedString($this->getParam("enc_event_id"), "decode");
                $model = new Application_Model_Common();

                $record = $model->getdata(TABLE_EVENTS, "event_id=$event_id");
                $event_type = $record["event_type"];

                $ej_is_accepted = "1";
                if ($event_type == "public")
                    $ej_is_accepted = "1";
                else
                    $ej_is_accepted = "0";

                $data_array = array(
                    "ej_event_id" => $event_id,
                    "ej_user_id" => $user_id,
                    "ej_is_accepted" => $ej_is_accepted,
                    "from_ipaddress" => $_SERVER["REMOTE_ADDR"]
                );

                $whereCond = "ej_event_id = $event_id and ej_user_id = $user_id";
                $is_exists = $model->is_exists(TABLE_EVENT_JOIN, $whereCond);

                if (empty($is_exists))
                {
                    $model->insertRecordData($data_array, TABLE_EVENT_JOIN);
                }
                else
                {
                    $data_array["ej_is_invited"] = "0";
//                    prd($data_array);
                    $model->updateRecordData($data_array, $whereCond, TABLE_EVENT_JOIN);
                }

                if ($event_type == "public")
                {

                    //send notification to host - status code 5 
                    $this->addNotification($record["event_created_by"], 5, $event_id, $user_id);

                    //send notification to user - status code 5
                    $this->addNotification($this->user_id, 5, $event_id);
                }
                else
                {
                    //send notification to host - status code 1 
                    $this->addNotification($record["event_created_by"], 1, $event_id, $user_id);
                }


                $this->redirect("eventdetail/" . $this->getParam("enc_event_id"));
            }
        }

        public function leaveeventAction()
        {
            if ($this->getParam("enc_event_id") && isset($this->user_id))
            {
                $user_id = $this->user_id;
                $event_id = getEncryptedString($this->getParam("enc_event_id"), "decode");

                $model = new Application_Model_Common();

                $record = $model->getdata(TABLE_EVENTS, "event_id = " . $event_id);

                //send notification to host - status code 2 - leaving an event 
                $this->addNotification($record["event_created_by"], 2, $event_id, $user_id);

                //send notification to user - status code 2 
                $this->addNotification($this->user_id, 2, $event_id);


                $model->deleteRecord("ej_event_id= $event_id and ej_user_id=$user_id", TABLE_EVENT_JOIN);
                $this->redirect("eventdetail/" . $this->getParam("enc_event_id"));
            }
        }

        public function celebrityeventsAction()
        {
            $page = $this->_getParam('page', 1);
            $model = new Application_Model_Common();
            $celeb_event_records = $model->getAllRecordDetail(TABLE_EVENTS, "event_celebrity_event='1' AND event_active='1'", "event_id", NULL, true)->limitPage($page, 10)->query()->fetchAll();

            //pagination
            $celeb_event_records_adapter = $model->getAllRecordDetail(TABLE_EVENTS, "event_celebrity_event='1' AND event_active='1'", "event_id", NULL, true);
            $adapter = new Zend_Paginator_Adapter_DbSelect($celeb_event_records_adapter);
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(10);
            $paginator->setCurrentPageNumber($page);
            $this->view->paginator = $paginator;

            foreach ($celeb_event_records as $key => $value)
            {
                $whereCond = "ej_event_id = " . $value["event_id"];
                $spots_booked_records = $model->getTotalCount("ej_id", TABLE_EVENT_JOIN, $whereCond);
                $celeb_event_records[$key]["remaining_spots"] = $value["event_group_size"] - $spots_booked_records["totalcount"];
            }

            $this->view->alldata = $celeb_event_records;
        }

        public function sponsoredeventsAction()
        {
            $page = $this->_getParam("page", 1);
            $custom_model = new Application_Model_Custom();
            $model = new Application_Model_Common();
            $records = $custom_model->getAllEventDetails("category_name LIKE '%Sports%'", "event_id", NULL, true)->limitPage($page, 10)->query()->fetchAll();

            //pagination
            $records_adapter = $custom_model->getAllEventDetails("category_name LIKE '%Sports%'", "event_id", NULL, true);
            $adapter = new Zend_Paginator_Adapter_DbSelect($records_adapter);
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(10);
            $paginator->setCurrentPageNumber($page);
            $this->view->paginator = $paginator;


            foreach ($records as $key => $value)
            {
                $whereCond = "ej_event_id = " . $value["event_id"];
                $spots_booked_records = $model->getTotalCount("ej_id", TABLE_EVENT_JOIN, $whereCond);
                $records[$key]["remaining_spots"] = $value["event_group_size"] - $spots_booked_records["totalcount"];
            }

            $this->view->alldata = $records;
        }

        public function searchAction()
        {
            $model = new Application_Model_Common();
            $custom_model = new Application_Model_Custom();
            $page = $this->_getParam("page", 1);
            $all_event_where_cond = "event_active = '1'";

            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
//                prd($arr);
                $event_type = trim($arr["event_type"]);
                $category_id = trim($arr["category_id"]);
                $subcategory_id = trim($arr["subcategory_id"]);
                $location = trim($arr["location"]);
//                $country_id = trim($arr["country_id"]);
//                $city_name = trim($arr["city_name"]);
                $query = trim($arr["query"]);
                if ($query == "Search")
                    $query = "";

                $subcategory_name = "";
                if (!empty($subcategory_id))
                {
                    $subcategory_record = $model->getdata(TABLE_SUB_CATEGORY, "subcategory_id=$subcategory_id");
                    $subcategory_name = trim($subcategory_record["subcategory_name"]);
                }

                $category_name = "";
                if (!empty($category_id))
                {
                    $category_record = $model->getdata(TABLE_CATEGORY, "category_id=$category_id");
                    $category_name = trim($category_record["category_name"]);
                }

                $_SESSION["search"]["event_type"] = $event_type;
                $_SESSION["search"]["category_id"] = $category_id;
                $_SESSION["search"]["category_name"] = $category_name;
                $_SESSION["search"]["subcategory_id"] = $subcategory_id;
                $_SESSION["search"]["subcategory_name"] = $subcategory_name;
//                $_SESSION["search"]["country_id"] = $country_id;
//                $_SESSION["search"]["city_name"] = $city_name;
                $_SESSION["search"]["location"] = $location;
                $_SESSION["search"]["query"] = $query;

//                prd($_SESSION);
//                $zip_code = trim($arr["zip_code"]);
//                if ($zip_code == "Zip Code")
//                    $zip_code = "";

                $where_array = array();
                if (!empty($event_type))
                    $where_array[] = "event_type = '$event_type'";
//
//                if (!empty($category_id))
//                    $where_array[] = "c.category_id = '$category_id'";
//
//                if (!empty($subcategory_id))
//                    $where_array[] = "sc.subcategory_id = '$subcategory_id'";

                if (!empty($subcategory_id))
                {
                    if (!empty($category_id))
                    {
                        $where_array[] = "(sc.subcategory_id = '$subcategory_id' AND c.category_id = '$category_id')";
                    }
                    else
                    {
                        $where_array[] = "sc.subcategory_id = '$subcategory_id'";
                    }
                }

                if (!empty($location))
                    $where_array[] = "e.event_location LIKE '%$location%'";

//                if (!empty($city_name))
//                    $where_array[] = "e.event_city = '$city_name'";
//
//                if (!empty($country_id))
//                {
//                    $country_id_arr = $model->getdata(TABLE_COUNTRY, "country_name = '" . $country_id . "'");
//                    $country_id = $country_id_arr["country_id"];
//                    $where_array[] = "country_id = '$country_id'";
//                }
//                if (!empty($zip_code))
//                    $where_array[] = "event_address LIKE '%$zip_code%'";

                if (!empty($query))
                    $where_array = "event_title LIKE '%$query%' OR 
                                                    event_address LIKE '%$query%' OR 
                                                        event_city LIKE '%$query%' OR 
                                                            event_group_type LIKE '%$query%' OR 
                                                                event_info LIKE '%$query%'
                        ";

                if (!empty($where_array))
                    $all_event_where_cond = implode(" OR ", $where_array);

                $all_event_records = $custom_model->getAllEventDetails($all_event_where_cond, "event_id DESC", NULL, true)->limitPage($page, 10)->query()->fetchAll();

                $this->view->allEvents = $all_event_records;

                $all_event_records_paging = $custom_model->getAllEventDetails($all_event_where_cond, "event_id DESC", NULL, true);
                $adapter = new Zend_Paginator_Adapter_DbSelect($all_event_records_paging);
                $paginator = new Zend_Paginator($adapter);
                $paginator->setItemCountPerPage(10);
                $paginator->setCurrentPageNumber($page);
                $this->view->paginator = $paginator;

                if (empty($subcategory_id))
                    $sponsoredWhere = "1";
                else
                    $sponsoredWhere = "event_subcat_id = $subcategory_id AND event_active = '1'";

                $celebrity_records = $model->getAllRecordDetail(TABLE_EVENTS, "event_celebrity_event = '1' AND event_active='1'", "rand()", "4");
                $sponsored_events = $custom_model->getAllEventDetails($sponsoredWhere, "rand()", "5");
                $this->view->celebrityEvents = $celebrity_records;
                $this->view->sponsoredEvents = $sponsored_events;

                $this->renderScript("index/index.phtml");
            }
            elseif ($this->getParam("getsearch"))
            {
                $arr = $this->getAllParams();
//                prd($arr);
                $event_type = trim($arr["event_type"]);
                $subcategory_id = trim($arr["subcategory_id"]);
                $category_id = trim($arr["category_id"]);
                $location = trim($arr["location"]);

                $getDistance = FALSE;
                if (!empty($location))
                {
                    $getDistance = TRUE;
                }

//                $country_id = trim($arr["country_id"]);
//                $city_name = trim($arr["city_name"]);
                $query = trim($arr["query"]);
                if ($query == "Search")
                    $query = "";

                $subcategory_name = "";
                if (!empty($subcategory_id))
                {
                    $subcategory_record = $model->getdata(TABLE_SUB_CATEGORY, "subcategory_id=$subcategory_id");
                    $subcategory_name = trim($subcategory_record["subcategory_name"]);
                }

                $category_name = "";
                if (!empty($category_id))
                {
                    $category_record = $model->getdata(TABLE_CATEGORY, "category_id=$category_id");
                    $category_name = trim($category_record["category_name"]);
                }

                $_SESSION["search"]["event_type"] = $event_type;
                $_SESSION["search"]["category_id"] = $category_id;
                $_SESSION["search"]["category_name"] = $category_name;
                $_SESSION["search"]["subcategory_id"] = $subcategory_id;
                $_SESSION["search"]["subcategory_name"] = $subcategory_name;
//                $_SESSION["search"]["country_id"] = $country_id;
//                $_SESSION["search"]["city_name"] = $city_name;
                $_SESSION["search"]["location"] = $location;
                $_SESSION["search"]["query"] = $query;

//                prd($_SESSION);
//                $zip_code = trim($arr["zip_code"]);
//                if ($zip_code == "Zip Code")
//                    $zip_code = "";

                $where_array = array();
                if (!empty($event_type))
                    $where_array[] = "event_type = '$event_type'";

//                if (!empty($category_id) && empty($subcategory_id))
//                    $where_array[] = "c.category_id = '$category_id'";
//
//                if (!empty($subcategory_id))
//                    $where_array[] = "sc.subcategory_id = '$subcategory_id'";

                if (!empty($subcategory_id))
                {
                    if (!empty($category_id))
                    {
                        $where_array[] = "(sc.subcategory_id = '$subcategory_id' AND c.category_id = '$category_id')";
                    }
                    else
                    {
                        $where_array[] = "sc.subcategory_id = '$subcategory_id'";
                    }
                }

//                if (!empty($location))
//                    $where_array[] = "e.event_location LIKE '%$location%'";
//                if (!empty($city_name))
//                    $where_array[] = "e.event_city = '$city_name'";
//
//                if (!empty($country_id))
//                {
//                    $country_id_arr = $model->getdata(TABLE_COUNTRY, "country_name = '" . $country_id . "'");
//                    $country_id = $country_id_arr["country_id"];
//                    $where_array[] = "country_id = '$country_id'";
//                }
//                if (!empty($zip_code))
//                    $where_array[] = "event_address LIKE '%$zip_code%'";
//                if (!empty($query))
//                    $where_array[] = "event_title LIKE '%$query%' OR 
//                                                    event_address LIKE '%$query%' OR 
//                                                        event_city LIKE '%$query%' OR 
//                                                            event_group_type LIKE '%$query%' OR 
//                                                                event_info LIKE '%$query%'
//                        ";


                if (empty($category_id))
                {
                    if (!empty($query) && empty($subcategory_id))
                    {
                        $where_array[] = "sc.subcategory_name LIKE '%$query%'";
                    }
                }
                else
                {
                    if (!empty($query) && empty($subcategory_id))
                    {
                        $where_array[] = "sc.subcategory_name LIKE '%$query%'";
                    }
                    else if (empty($query) && empty($subcategory_id) && !empty($category_id))
                    {
                        $where_array[] = "c.category_id = '$category_id'";
                    }
                }

                if (!empty($where_array))
                {
                    $all_event_where_cond = implode(" OR ", $where_array);
                    $all_event_where_cond = "(" . $all_event_where_cond . ")";
                    $all_event_where_cond .= " AND event_active = '1'";
                }

                if (empty($all_event_where_cond))
                    $all_event_where_cond = "event_active = '1'";

//                prd($all_event_where_cond);

                $sort_tag_class = "distance";
                if ($this->getParam("sort_type"))
                {
                    $sort_type = trim($this->getParam("sort_type"));

                    switch ($sort_type)
                    {
                        case "date":
                            {
                                $all_event_order_by = "event_id DESC";
                                $sort_tag_class = "date";
                                break;
                            }
                        case "groupsize":
                            {
                                $all_event_order_by = "event_group_size DESC";
                                $sort_tag_class = "groupsize";
                                break;
                            }
                        case "distance":
                            {
                                $all_event_order_by = "event_id DESC";
                                $sort_tag_class = "distance";
                                break;
                            }
                    }
                }
                $this->view->sort_tag_class = $sort_tag_class;



//                prd($all_event_where_cond);

                $all_event_records = $custom_model->getAllEventDetails($all_event_where_cond, "event_id DESC", NULL, true)->limitPage($page, 10)->query()->fetchAll();

                if ($sort_tag_class == "distance")
                {
                    if ($getDistance)
                    {
                        foreach ($all_event_records as $new_key => $new_value)
                        {
                            $event_address = stripslashes(trim($new_value["event_address"] . ", " . $new_value["event_location"]));
//                            $event_distance = getCurrentEventDistance($event_address, NULL, "M", FALSE);
                            $event_distance = getEventDistanceAway($event_address, $location);
//                            pr($event_distance);
                            $all_event_records[$new_key]["event_distance_to_sort"] = $event_distance;
                        }
//                        die;

                        sksort($all_event_records, "event_distance_to_sort", TRUE);
                    }
                }
                else if ($sort_tag_class == "date")
                {
                    foreach ($all_event_records as $new_key => $new_value)
                    {
                        $getEventDate = strtotime(getEventDate($new_value["event_date"]));
                        $all_event_records[$new_key]["event_new_date_to_sort"] = $getEventDate;
                    }

                    sksort($all_event_records, "event_new_date_to_sort");
                }


                $this->view->allEvents = $all_event_records;

                $all_event_records_paging = $custom_model->getAllEventDetails($all_event_where_cond, "event_id DESC", NULL, true);
                $adapter = new Zend_Paginator_Adapter_DbSelect($all_event_records_paging);
                $paginator = new Zend_Paginator($adapter);
                $paginator->setItemCountPerPage(10);
                $paginator->setCurrentPageNumber($page);
                $this->view->paginator = $paginator;

                if (empty($subcategory_id))
                    $sponsoredWhere = "event_active = '1'";
                else
                    $sponsoredWhere = "event_subcat_id = $subcategory_id AND event_active = '1'";

                $celebrity_records = $model->getAllRecordDetail(TABLE_EVENTS, "event_celebrity_event = '1' AND event_active='1'", "rand()", "4");
                $sponsored_events = $custom_model->getAllEventDetails($sponsoredWhere, "rand()", "5");
                $this->view->celebrityEvents = $celebrity_records;
                $this->view->sponsoredEvents = $sponsored_events;

                $this->view->another_address = $location;

                $this->renderScript("index/index.phtml");
            }
            elseif ($this->getParam("cat_search") || $this->getParam("subcat_search"))
            {
                if ($this->getParam("cat_search"))
                {
                    $all_event_where_cond = "event_cat_id = " . $this->getParam("cat_search");
                    $category_id = $this->getParam("cat_search");
                }

                if ($this->getParam("subcat_search"))
                {
                    $all_event_where_cond = "event_subcat_id = " . $this->getParam("subcat_search");
                    $fetch = $model->getdata(TABLE_SUB_CATEGORY, "subcategory_id=" . $this->getParam("subcat_search"));
                    $category_id = $fetch["category_id"];
                }

                $all_event_records = $custom_model->getAllEventDetails($all_event_where_cond, "event_id DESC", NULL, true)->limitPage($page, 10)->query()->fetchAll();

                $this->view->allEvents = $all_event_records;

                $all_event_records_paging = $custom_model->getAllEventDetails($all_event_where_cond, "event_id DESC", NULL, true);
                $adapter = new Zend_Paginator_Adapter_DbSelect($all_event_records_paging);
                $paginator = new Zend_Paginator($adapter);
                $paginator->setItemCountPerPage(10);
                $paginator->setCurrentPageNumber($page);
                $this->view->paginator = $paginator;

                if (empty($category_id))
                    $sponsoredWhere = "1";
                else
                    $sponsoredWhere = "event_cat_id = $category_id";

                $celebrity_records = $model->getAllRecordDetail(TABLE_EVENTS, "event_celebrity_event = '1' AND event_active='1'", "rand()", "4");
                $sponsored_events = $custom_model->getAllEventDetails($sponsoredWhere, "rand()", "5");
                $this->view->celebrityEvents = $celebrity_records;
                $this->view->sponsoredEvents = $sponsored_events;

                $this->renderScript("index/index.phtml");
            }
            else
            {
                $this->baseUrl("");
            }
        }

        public function eventupdatesAction()
        {
            $model = new Application_Model_Custom();
            //$whereCond = "no_notification NOT IN (SELECT no_notification FROM " . TABLE_USERS . " WHERE user_id = '" . $this->user_id . "')";
            $whereCond = " notification_user_id = " . $this->user_id . " and notification_status = '1'";


            $page = $this->_getParam("page", 1);
            $records = $model->getUserNotifications($this->user_id, false, false, true)->limitPage($page, 10)->query()->fetchAll();

            $this->view->alldata = $records;

            $eventupdatesAdapter = $model->getUserNotifications($this->user_id, false, false, true);

            $adapter = new Zend_Paginator_Adapter_DbSelect($eventupdatesAdapter);
            $paginator = new Zend_Paginator($adapter);
            $paginator->setItemCountPerPage(10);
            $paginator->setCurrentPageNumber($page);
            $this->view->paginator = $paginator;
        }

        public function addNotification($userId, $statusCode, $eventId, $joiner_id = false)
        {
            $data_array['notification_user_id'] = $userId;
            $data_array['notification_code'] = $statusCode;
            $data_array['notification_event_id'] = $eventId;

            if ($joiner_id)
                $data_array['notification_event_joiner'] = $joiner_id;

            $result = $this->commonModel->insertRecordData($data_array, TABLE_NOTIFICATION);
        }

        private function getMyEvents($userId)
        {
            $commonModel = new Application_Model_Common();
            $result = $commonModel->getAllRecordDetail(TABLE_EVENTS, "event_created_by = " . $userId);

            $arr = array();
            foreach ($result as $val)
            {
                $arr[] = $val['event_id'];
            }
            return $arr;
        }

        function removenotificationAction()
        {

            $commonModel = new Application_Model_Common();
            $notification_id = $this->_getParam("nId");

            if (empty($this->user_id))
            {
                $this->_redirect("");
            }

            if (!empty($notification_id))
            {

                $data_array['notification_status'] = '0';
                $commonModel->updateRecordData($data_array, "notification_id = " . $notification_id, TABLE_NOTIFICATION);
            }

            $this->_redirect("event/eventupdates");
        }

        public function deleteeventAction()
        {
//            $this->_helper->viewRenderer->setNoRender();
            if ($this->getParam("event_id"))
            {

                $event_id = trim($this->getParam("event_id"));

                $model = new Application_Model_Common();
                $email_model = new Application_Model_Email();

                $event_records = $model->getdata(TABLE_EVENTS, "event_id=$event_id");
                $event_title = $event_records["event_title"];

                $records = $model->getAllRecordFromInnerJoin(array("ej" => TABLE_EVENT_JOIN), array("u" => TABLE_USERS), "u.user_id=ej.ej_user_id", "ej_event_id=$event_id");
                //prd($records);
                if (!empty($records))
                {
                    $email_records = $model->getdata(TABLE_EMAIL_TEMPLATES, "et_key='event_delete_email_to_attendees'");

                    foreach ($records as $key => $value)
                    {
                        $user_full_name = $value["user_first_name"] . " " . $value["user_last_name"];
                        $user_email = $value["user_email"];

                        $messageContent = $email_records["et_content"];
                        $messageContent = str_replace("{event_title}", $event_title, $messageContent);
                        $messageContent = str_replace("{user_name}", $user_full_name, $messageContent);

                        $email_model->sendMail($user_email, SITE_EMAIL, SITE_NAME, $email_records["et_subject"], $messageContent);
                    }

                    $this->addNotificationToAllUsers($event_id, 10);
                }

                $model->deleteRecord("event_id=$event_id", TABLE_EVENTS);
                //$model->deleteRecord("ej_event_id=$event_id", TABLE_EVENT_JOIN);
                $model->deleteRecord("ec_event_id=$event_id", TABLE_EVENT_CHAT);
                $model->deleteRecord("ecm_event_id=$event_id", TABLE_EVENT_COMMENTS);
                $model->deleteRecord("eb_event_id=$event_id", TABLE_EVENT_BOOKMARK);

                $event_pics_dir = "resources/event-pics/" . getEncryptedString($event_id);
                deleteDirectory($event_pics_dir);
                die;
            }
            die;
        }

        function addNotificationToAllUsers($event_id, $statusCode)
        {
            $usersData = $this->commonModel->getAllRecordDetail(TABLE_EVENT_JOIN, "ej_event_id = " . $event_id . " and ej_is_accepted = '1'");

            //prd($usersData);
            $event_detail = $this->commonModel->getdata(TABLE_EVENTS, "event_id = " . $event_id);


            $data_array['notification_code'] = $statusCode;
            $data_array['notification_event_id'] = $event_id;

            if ($statusCode == '10')
            { // delete event notification
                $data_array['notification_message'] = $event_detail['event_title'] . " has been removed";
                $data_array['notification_notify'] = json_encode($event_detail);
            }

            foreach ($usersData as $value)
            {
                $data_array['notification_user_id'] = $value['ej_user_id'];

                $result = $this->commonModel->insertRecordData($data_array, TABLE_NOTIFICATION);
            }
        }

        public function getWhoRatedAndCommentsOnUser($user_id)
        {
            $model = new Application_Model_Common;
            $records = $model->getAdapter()->select()
                    ->from(array("ur" => TABLE_RATING))
                    ->joinLeft(array("u" => TABLE_USERS), "u.user_id=ur.user_rate_from")
                    ->where("ur.user_rate_to = $user_id")
                    ->order("ur.rating_id DESC")
                    ->limit("3");
            $records = $records->query()->fetchAll();

            foreach ($records as $key => $value)
            {
                $whereCond = "user_rate_to = $user_id AND user_rate_from = " . $value["user_id"];
                $result = $model->getdata(TABLE_RATING, $whereCond);
                $records[$key]["stars_rated"] = $result["rating"];
            }
//            prd($records);
            return $records;
        }

        function getCreatedEvent($user_id, $where = NULL)
        {
            if ($where == NULL)
//                $where = "event_created_by = $user_id AND event_ended = '0'";
                $where = "event_created_by = $user_id";

            $custom_model = new Application_Model_Custom();
            $records = $custom_model->getAllEventDetails($where, "event_id DESC", "3");
            return $records;
        }

    }

    